package com.allenz.forum.controller;

import com.allenz.forum.common.AppResult;
import com.allenz.forum.common.ResultCode;
import com.allenz.forum.config.AppConfig;
import com.allenz.forum.model.User;
import com.allenz.forum.services.IUserService;
import com.allenz.forum.utils.MD5Util;
import com.allenz.forum.utils.StringUtil;
import com.allenz.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.core.io.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;

// 对 controller 进行API接口的描述
@Api(tags = "用户接口")
// 日志注解
@Slf4j
// 返回数据的 controller
@RestController
// 一级路由
@RequestMapping("/user")
public class UserController {

    @javax.annotation.Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRepeat 重复密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register (@ApiParam("用户名") @RequestParam("username") @NonNull String username ,
                               @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname ,
                               @ApiParam("密码") @RequestParam("password") @NonNull String password ,
                               @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        // 校验密码与重复密码是否一致
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 处理密码
        // 1. 生成盐
        String salt = UUIDUtil.UUID_32();
        // 2. 生成密码的密文
        String encryptPassword = MD5Util.md5Salt(password , salt);
        // 3. 设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        // 调用 Service 层
        userService.createNormalUser(user);

        // 返回成功
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param request
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 1．调用Service中的登录方法，返回User对象
        User user = userService.login(username, password);
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        // 2．如果登录成功把 User 对象设置到 Session 作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION , user);
        // 3．返回结果
        return AppResult.success();
    }

    /**
     * 获取用户信息
     * @param request
     * @param id
     * @return
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request ,
                                       @ApiParam("用户Id") @RequestParam(value = "id",required = false) Long id){
        User user = null;
        if (id == null){
            // 1. 如果 id 为空 , 从当前登录 session 中获取用户信息
            HttpSession session = request.getSession(false);
            // 从 session 中获取当前用户信息+-+
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            // 2. 如果 id 不为空 , 从数据库查询用户信息
            user = userService.selectById(id);
            // 判断用户对象是否为空
            if (user == null){
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            }
        }
        // 返回结果
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        // 获取 session 对象
        HttpSession session = request.getSession(false);
        // 判断 session 是否有效
        if (session != null){
            // 打印日志
            log.info("退出成功!");
            // 表示用户在登录状态 , 直接销毁 session
            // invalidate 表示销毁session并解绑信息
            session.invalidate();
        }
        return AppResult.success("退出成功!");
    }

    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号码
     * @param remark 个人简介
     * @return AppResult
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request ,
                                @ApiParam("用户名") @RequestParam(value = "username" , required = false) String username ,
                                @ApiParam("昵称") @RequestParam(value = "nickname" , required = false) String nickname ,
                                @ApiParam("性别") @RequestParam(value = "gender" , required = false) Byte gender ,
                                @ApiParam("邮箱") @RequestParam(value = "email" , required = false) String email ,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum" , required = false) String phoneNum ,
                                @ApiParam("个人简介") @RequestParam(value = "remark" , required = false) String remark
                                ){
        // 1. 接收参数
        // 2. 对参数进行非空校验 , 全部为空则返回错误描述
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null){
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容!");
        }

        // 3. 封装对象
        // 从session中获取用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话号码
        updateUser.setRemark(remark); // 个人简介

        // 4. 调用 Service
        userService.modifyInfo(updateUser);

        // 5. 查询最新的用户信息

        user = userService.selectById(user.getId());

        // 6. 把最新的user信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION,user);

        // 7. 返回结果
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request ,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword ,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword ,
                                    @ApiParam("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)){
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调用 Service
        userService.modifyPassword(user.getId() , newPassword , oldPassword);
        // 4. 销毁 session
        if (session != null){
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();
    }
    @ApiOperation("修改背景")
    @PostMapping("/NewBackground")
    public AppResult modifyBackground(HttpServletRequest request ,
                                      @ApiParam("背景") @RequestParam("image") MultipartFile image){
        // 2. 获取当前用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 查询用户ID
        user = userService.selectById(user.getId());

        Long userId = user.getId();
        // 4.调用Service
        userService.saveImage(userId,image);

        return AppResult.success();
    }
    @ApiOperation("读取背景图")
    @GetMapping("/getBackgroundImage")
    public ResponseEntity<Resource> getBackgroundImage(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 查询用户ID
        user = userService.selectById(user.getId());

        Long userId = user.getId();
        // 从数据库获取图片数据
        byte[] imageData = userService.getBackgroundImageFromDatabase(userId);
        // 将字节数组转换为图片文件
        Resource resource = new ByteArrayResource(imageData);
        // 设置响应头，告诉前端返回的是图片文件
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        // 返回图片文件
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);
    }


}

